package com.aaa.dao;

import com.aaa.entity.Ftype;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
public class FtypeDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    private RowMapper<Ftype> rowMapper=new RowMapper<Ftype>() {
        public Ftype mapRow(ResultSet resultSet, int i) throws SQLException {
            Ftype ftype=new Ftype();
            ftype.setTid(resultSet.getLong("tid"));
            ftype.setName(resultSet.getString("name"));
            return ftype;
        }
    };


    public List<Ftype> listAll(){

        String sql="select tid,name from ftype";
        List<Ftype> result=jdbcTemplate.query(sql,rowMapper);
        return result;
    }

    public List<Ftype> listPage(String keyword,Integer offset,Integer limit){
        String sql="select tid,name from ftype where name like ? order by tid desc limit ?,?";
        List<Ftype> result = jdbcTemplate.query(sql, rowMapper, "%" + keyword + "%",offset,limit);
        return result;
    }


    public Integer count(String keyword){
        String sql="select count(tid) as c from ftype where name like ?";
        final Integer result=jdbcTemplate.queryForObject(sql, new RowMapper<Integer>() {
            public Integer mapRow(ResultSet resultSet, int i) throws SQLException {
                return resultSet.getInt("c");
            }
        },"%"+keyword+"%");
        return result;
    }


    public Integer save(Ftype ftype){
        String sql="insert into ftype(name) values(?)";
        int count = jdbcTemplate.update(sql, ftype.getName());
        return count;
    }


    public Integer update(Ftype ftype){
        String sql="update ftype set name=? where tid=?";
        int count = jdbcTemplate.update(sql, ftype.getName(), ftype.getTid());
        return count;
    }



}
